import os
import logging
from typing import List, Optional, Dict, Any
import asyncio
from pathlib import Path

# 尝试导入各种文档处理库
try:
    from langchain_community.document_loaders import (
        TextLoader, 
        PyPDFLoader, 
        Docx2txtLoader,
        UnstructuredExcelLoader,
        CSVLoader,
        UnstructuredPowerPointLoader
    )
    from langchain.schema import Document
    LANGCHAIN_AVAILABLE = True
except ImportError:
    logging.warning("Langchain文档处理库未安装，文档处理功能将受限")
    LANGCHAIN_AVAILABLE = False
    
    # 创建一个简单的Document类作为替代
    class Document:
        def __init__(self, page_content: str, metadata: Dict[str, Any] = None):
            self.page_content = page_content
            self.metadata = metadata or {}

async def load_document(file_path: str) -> Optional[List[Document]]:
    """
    根据文件类型加载文档
    
    Args:
        file_path: 文件路径
        
    Returns:
        文档对象列表，如果加载失败则返回None
    """
    if not os.path.exists(file_path):
        logging.error(f"文件不存在: {file_path}")
        return None
        
    file_ext = Path(file_path).suffix.lower()
    
    try:
        # 如果没有安装langchain，使用基础文本加载
        if not LANGCHAIN_AVAILABLE:
            if file_ext in ['.txt', '.md', '.json', '.csv', '.yaml', '.yml']:
                return await load_text_fallback(file_path)
            else:
                logging.error(f"无法处理文件类型: {file_ext}，Langchain库未安装")
                return None
                
        # 使用适当的加载器
        if file_ext == '.pdf':
            return await load_with_loader(PyPDFLoader(file_path))
        elif file_ext in ['.docx', '.doc']:
            return await load_with_loader(Docx2txtLoader(file_path))
        elif file_ext in ['.xlsx', '.xls']:
            return await load_with_loader(UnstructuredExcelLoader(file_path))
        elif file_ext == '.csv':
            return await load_with_loader(CSVLoader(file_path))
        elif file_ext in ['.pptx', '.ppt']:
            return await load_with_loader(UnstructuredPowerPointLoader(file_path))
        elif file_ext in ['.txt', '.md', '.json', '.yaml', '.yml']:
            return await load_with_loader(TextLoader(file_path, encoding='utf-8'))
        else:
            logging.warning(f"未知文件类型: {file_ext}，尝试作为文本加载")
            return await load_with_loader(TextLoader(file_path, encoding='utf-8'))
            
    except Exception as e:
        logging.error(f"加载文档失败: {str(e)}")
        return None
        
async def load_with_loader(loader) -> List[Document]:
    """使用指定的加载器异步加载文档"""
    return await asyncio.to_thread(lambda: loader.load())
    
async def load_text_fallback(file_path: str) -> List[Document]:
    """基础文本加载的替代方案"""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
            
        return [Document(
            page_content=content,
            metadata={"source": file_path}
        )]
    except Exception as e:
        logging.error(f"基础文本加载失败: {str(e)}")
        return None 